
package uestc.bitman.edxapp.mainui;

import uestc.bitman.edxapp.EdxApp;
import uestc.bitman.edxapp.EdxStudentUser;
import uestc.bitman.edxapp.R;
import uestc.bitman.edxapp.courselist.MyCourseListFragment;
import uestc.bitman.edxapp.courses.CoursesFragment;
import uestc.bitman.edxapp.downloaded.DownloadedFragment;
import uestc.bitman.edxapp.downloading.DownloadFragment;
import uestc.bitman.edxapp.downloading.DownloadingTaskAdapter;
import uestc.bitman.edxapp.misc.AboutFragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MainUIController extends PressAgainExitController {

    private MyCourseListFragment mCourseListFragment = null;

    private CoursesFragment mCoursesFragment = null;

    private DownloadFragment mDownloadFragment = null;

    private DownloadedFragment mDownloadedFragment = null;

    private AboutFragment mAboutFragment = null;

    private DrawerLayout mDrawerLayout;

    private ActionBarDrawerToggle mDrawerToggle;

    private ListView mListView;

    private DrawerAdapter mDrawerAdapter;

    private EdxStudentUser user;

    private OnItemClickListener mDrawerListener;

    private Activity mActivity;

    public void initController(Activity activity) {
        mActivity = activity;
        super.initController(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        mActivity.setContentView(R.layout.activity_main);

        user = EdxApp.getEdxAppUser();

        initDrawer();

        EdxApp.setDownloadingTaskAdapter(new DownloadingTaskAdapter(mActivity));

        if (savedInstanceState == null && user.isLogin()) {
            mCourseListFragment = new MyCourseListFragment();
            mActivity.getFragmentManager().beginTransaction()
                    .replace(R.id.content_frame, mCourseListFragment).commit();
        } else if (!user.isLogin()) {
            UserLoginTask loginTask = new UserLoginTask();
            loginTask.execute(mLoginListener);
        }
    }

    public void handleBackPress() {
        
    }

    private void initDrawer() {

        mActivity.getActionBar().setDisplayHomeAsUpEnabled(true);
        mActivity.getActionBar().setHomeButtonEnabled(true);
        mDrawerLayout = (DrawerLayout) mActivity.findViewById(R.id.drawer_layout);
        mListView = (ListView) mActivity.findViewById(R.id.left_drawer);
        mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        mDrawerAdapter = new DrawerAdapter(mActivity);
        mListView.setAdapter(mDrawerAdapter);

        mDrawerLayout.setDrawerListener(setUpDrawerToggle());
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        mDrawerListener = new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {

                replaceCategoryFragment(pos);
                mListView.setItemChecked(pos, true);
                mDrawerLayout.closeDrawer(mListView);
            }
        };
        mListView.setOnItemClickListener(mDrawerListener);
        // show the drawer automatically
        // mDrawerLayout.openDrawer(mListView);
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState) {

        mDrawerToggle.syncState();
    }

    private void replaceCategoryFragment(int position) {

        mActivity.setTitle(mDrawerAdapter.getItem(position));
        switch (position) {
            case 0:
                mActivity.getFragmentManager().popBackStack(null,
                        FragmentManager.POP_BACK_STACK_INCLUSIVE);
                if (mCoursesFragment == null) {
                    mCoursesFragment = new CoursesFragment();
                }
                switchFragment(mCoursesFragment, "courses", false, true);
                break;
            case 1:
                mActivity.getFragmentManager().popBackStack(null,
                        FragmentManager.POP_BACK_STACK_INCLUSIVE);
                if (mCourseListFragment == null) {
                    mCourseListFragment = new MyCourseListFragment();
                }
                switchFragment(mCourseListFragment, "courseList", false, true);
                break;
            case 2:
                if (mDownloadFragment == null) {
                    mDownloadFragment = new DownloadFragment();
                }
                switchFragment(mDownloadFragment, "download", true, false);
                break;
            case 3:
                if (mDownloadedFragment == null) {
                    mDownloadedFragment = new DownloadedFragment();
                }
                switchFragment(mDownloadedFragment, "downloaded", true, false);
                break;
            case 4:
                user.logOut();
                user.saveLoginStatus(mActivity);
                Intent intent = new Intent(mActivity, MainUIActivity.class);
                intent.putExtra(MainUIActivity.TAG_ACTION, "login");
                mActivity.startActivity(intent);
                mActivity.finish();
                break;
            case 5:
                if (mAboutFragment == null) {
                    mAboutFragment = new AboutFragment();
                }
                switchFragment(mAboutFragment, "about", true, false);
            default:
                break;
        }
    }

    private void switchFragment(Fragment fragment, String tagString, boolean addToBackStack,
            boolean pressAgainExit) {

        enablePressAgainToExit(pressAgainExit);
        startFragment(fragment, tagString, addToBackStack);
    }

    private DrawerListener setUpDrawerToggle() {

        mDrawerToggle = new ActionBarDrawerToggle(mActivity, mDrawerLayout, R.drawable.ic_drawer,
                R.string.drawer_open_title, R.string.drawer_close_title) {
            @Override
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                mActivity.invalidateOptionsMenu();
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                mActivity.invalidateOptionsMenu();
            }
        };
        return mDrawerToggle;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // MenuInflater inflater = getMenuInflater();
        // mCurrentFragment.onCreateOptionsMenu(menu, inflater);
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        
        return false;
    }

    public void startFragment(Fragment fragment, String tagString, boolean addToBackStack) {

        FragmentManager fragmentManager = mActivity.getFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.content_frame, fragment, tagString);
        if (addToBackStack) {
            transaction.addToBackStack(tagString);
        }
        transaction.commit();
    }

    UserLoginListener mLoginListener = new UserLoginListener() {

        @Override
        public void onTimeOut() {
            
        }

        @Override
        public void onLoginResult(boolean result) {
            if (result) {
                mCourseListFragment = new MyCourseListFragment();
                mActivity.getFragmentManager().beginTransaction()
                        .replace(R.id.content_frame, mCourseListFragment).commit();
            }
        }

        @Override
        public void onCancel() {
            
        }
    };
}
